package com.jsmtr.rms.controller.writtentest;

import com.jsmtr.rms.dao.DaoService;
import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.IPaperManageService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.StringTools;
import com.jsmtr.rms.utils.WordHelper.WordByFreeMarker;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/PaperManager")
public class PaperManageController {

    @Resource
    private IUtilService utilService;

    @Resource
    IPaperManageService paperManageService;

    @Resource
    DaoService dao;

    @RequestMapping("/index")
    public String index(Model model) {
        try {
            List<BaseJob> baseJobs = paperManageService.getJobs();
            model.addAttribute("jobs",baseJobs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/index";
    }

    private static  String noFindResult = "可能由于题目被删除等情况，导致该试卷被抽查的题目存在异常，请尝试修改试卷，重新生成试卷," +
            "或者在试卷题目管理中选择新的题目。";

    @RequestMapping("/add")
    public String add(Model model,HttpServletRequest request) {
        try {
            String id = request.getParameter("id");
            PaperManage paperManage = null;

            if (StringTools.trimNotEmpty(id))
                paperManage=  paperManageService.getPaperManage(id);

            if(paperManage != null){
                model.addAttribute("id",paperManage.getId());
                model.addAttribute("paperName",paperManage.getName());
                model.addAttribute("paperType",paperManage.getType());
                model.addAttribute("paperPurpose",paperManage.getPurpose());
                model.addAttribute("position",paperManage.getPosition());
                model.addAttribute("totalScore",paperManage.getTotalScore());
                model.addAttribute("paperState",paperManage.getState());
                model.addAttribute("addName",paperManage.getAddName());
                model.addAttribute("addTime",DateTools.toLenStr(paperManage.getAddTime()));
                model.addAttribute("paperExplain",paperManage.getExplain());
            }else {
                model.addAttribute("paperType",0);
                model.addAttribute("paperPurpose",0);
                model.addAttribute("position","");
            }

            List<BaseJob> baseJobs = paperManageService.getJobs();
            model.addAttribute("jobs",baseJobs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/addPaper";
    }
    /**
     * 获取试卷列表
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/getPaperList", method = RequestMethod.GET)
    public LayuiDataTableResultBean getPaperList(HttpServletRequest request, HttpServletResponse response) {
        try {
            int curPage = Integer.parseInt(request.getParameter("page"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            String position = (request.getParameter("key[sPosition]")==null)?"":request.getParameter("key[sPosition]");
            String keyWord = (request.getParameter("key[sKey]")==null)?"":request.getParameter("key[sKey]");
            String orderKey = request.getParameter("orderKey");
            String orderType = request.getParameter("orderType");

            int purpose = -1;
            try {
                purpose = Integer.parseInt(request.getParameter("key[sPurpose]"));
            } catch (NumberFormatException ignored) {
            }

            Map<String, Object> map = paperManageService.getPaperList(curPage, pageSize, position,
                    purpose, keyWord, orderKey, orderType);
            double count = (double) map.get("count");
            double pageCount = (Double) map.get("pageCount");
            JSONArray jsonArray = new JSONArray();

            int num = 1;
            if (pageCount != 0) {
                Object object = map.get("list");
                for (PaperManage paperManage : (List<PaperManage>) object){
                    JSONObject jsonObject = JSONObject.fromObject(paperManage);
                    jsonObject.put("id_cb","cb_" + paperManage.getId());
                    jsonObject.put("id",pageSize * (curPage - 1) + num);
                    jsonObject.put("paperName", paperManage.getName());
                    jsonObject.put("paperPurpose",paperManage.getPurpose());
                    jsonObject.put("paperType",paperManage.getType());
                    jsonObject.put("position",paperManage.getPosition());
                    jsonObject.put("totalScore",paperManage.getTotalScore());
                    jsonObject.put("addName",paperManage.getAddName());
                    jsonObject.put("addTime",DateTools.toLenStr(paperManage.getAddTime()));
                    jsonObject.put("paperState",paperManage.getState());
                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) count);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getKnowlegeList", method = RequestMethod.GET)
    public LayuiDataTableResultBean getKnowlegeList(HttpServletRequest request, HttpServletResponse response) {
        try {
            int curPage = Integer.parseInt(request.getParameter("page"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            String keyWordType = (request.getParameter("key[tType]")==null)?"":request.getParameter("key[tType]");
            String keyWordPosition = (request.getParameter("key[tPosition]")==null)?"":request.getParameter("key[tPosition]");

            Map<String, Object> map = paperManageService.getKnowList(curPage, pageSize,keyWordPosition);
            List<KnowManage> knowManageLists = paperManageService.getKnowManageList();

            double count = (double) map.get("count");
            double pageCount = (Double) map.get("pageCount");
            JSONArray jsonArray = new JSONArray();

            if (pageCount != 0) {
                Object object = map.get("list");
                for (Knowledge knowledge : (List<Knowledge>) object){
                    JSONObject jsonObject = new JSONObject();
                    String[] kName =  getKname(knowManageLists, knowledge);
                    jsonObject.put("name",kName[0]);
                    jsonObject.put("kid",kName[1]);
                    jsonObject.put("major",knowledge.getName());
                    String[] getNum =  getKnum(keyWordType, knowledge,knowledge.getName());
                    jsonObject.put("type",keyWordType);
                    jsonObject.put("allnum",Integer.parseInt(getNum[0].equals("null")?"0":getNum[0]));
                    jsonObject.put("num",Integer.parseInt(getNum[1].equals("null")?"0":getNum[1]));
                    jsonArray.add(jsonObject);
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) count);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    private String[] getKnum(String kType, Knowledge kledge,String position) throws Exception {
        String getNum = "0,0";
        List<QuestionBank> questionBankList = paperManageService.getTopicListByKidPosition(kledge.getKid(),kType,position);
        switch (kType){
            case "单项选择题":
                getNum = questionBankList.size()+","+kledge.getSinglescount();
                break;
            case "不定项选择题":
                getNum = questionBankList.size()+","+kledge.getIndefiscount();
                break;
            case "填空题":
                getNum = questionBankList.size()+","+kledge.getFillscount();
                break;
            case "判断正误题":
                getNum = questionBankList.size()+","+kledge.getJudgescount();
                break;
            case "简答题":
                getNum = questionBankList.size()+","+kledge.getAnswerscount();
                break;
            case "综合题":
                getNum = questionBankList.size()+","+kledge.getSynthscount();
                break;
            default:break;
        }
        return  getNum.split(",");
    }

    private String[] getKname(List<KnowManage> klist, Knowledge kledge) {
        String[] namet = {"",""};
        for (KnowManage knowManage : klist ){
            if(knowManage.getId().equals(kledge.getKid())){
                namet[0] = knowManage.getName();
                namet[1] = knowManage.getId();
                break;
            }
        }
        return namet;
    }

    /**
     * 获取试卷组卷规则列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPaperContentList", method = RequestMethod.GET)
    public LayuiDataTableResultBean getPaperContentList(HttpServletRequest request, HttpServletResponse response) {
        try {
            int curPage = Integer.parseInt(request.getParameter("page"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));
            String id = request.getParameter("id");

            List<PaperContent> paperListTemp = new ArrayList<>();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            if (StringTools.trimNotEmpty(id)){

                paperListTemp=  paperManageService.getPapers(id);
                List<KnowManage> knowManageList =  paperManageService.getKnowManageList();

                Integer num = 0;
                JSONArray jsonArray = new JSONArray();
                if(paperListTemp.size() > 0){
                    for (PaperContent paperContent : (List<PaperContent>) paperListTemp){
                        JSONObject jsonObject = JSONObject.fromObject(paperContent);
                        jsonObject.put("idnum",num);
                        jsonObject.put("id",paperContent.getId());
                        jsonObject.put("paperChapter",paperContent.getChapter());
                        jsonObject.put("topicType",paperContent.getTopicType());
                        String kidTemp = paperContent.getKid();
                        jsonObject.put("kid",kidTemp);
                        String kname =  getkid(knowManageList, kidTemp);
                        jsonObject.put("rangeQuestion",kname);
                        jsonObject.put("totalTopics",paperContent.getTotalTopics());
                        jsonObject.put("scoreQuestion",paperContent.getScoreQuestion());
                        jsonObject.put("sort",paperContent.getSort());
                        jsonArray.add(jsonObject);
                        num++;
                    }
                }

                result.setCode(0);
                result.setMsg("success");
                result.setCount(num);
                result.setData(jsonArray);
            }else {
                result.setCount(-1);
                result.setMsg("err");
                return result;
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    private String getkid(List<KnowManage> klist, String kTemp) {
        String knameTemp = "";
        for(KnowManage knowManage : klist){
            if(knowManage.getId().equals(kTemp)){
                knameTemp = knowManage.getName();
                break;
            }
        }
        return knameTemp;
    }

    /**
     * 新增试卷
     * @param request
     * @param response
     */
    @RequestMapping(value = "/addPaper", method = RequestMethod.POST)
    public void addPaper(HttpServletRequest request, HttpServletResponse response,String listJson) {
        try {
            //获取前端数据
            PaperManage paperManageTemp = getPaperDataManage(request);
            paperManageTemp.setState("启用");

            JSONArray jsonArray = JSONArray.fromObject(request.getParameter("listJson"));
            List<PaperContent> paperListTemp = getPaperContentsListJson(jsonArray);

            List<QuestionBank> questionBankList = getQBanks(paperListTemp,paperManageTemp.getPosition());

            Integer flag = paperManageService.addPaper(paperManageTemp,paperListTemp,questionBankList,request);

            if(flag == 1)
                utilService.printJsonResult(true, "操作成功！", "no", response);
            else if(flag == 2)
                utilService.printJsonResult(false, "已存在相同名称的试卷！", "no", response);
            else
                utilService.printJsonResult(false, "操作失败！", "no", response);

        }catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    private String[] getKids(List<PaperContent> paperListTemp) {
        String[] knowledgeIDTemp = new String[paperListTemp.size()];
        String[] knowledgeID= new String[1];
        int num =0;
        if(paperListTemp.size()>0){
            knowledgeIDTemp[0] = paperListTemp.get(0).getKid();
        }
        if(paperListTemp.size()>1){
            for(int i=1;i<paperListTemp.size();i++){
                knowledgeIDTemp[i] = paperListTemp.get(i).getKid();
            }
            ArrayList list=new ArrayList();
            for (String s : knowledgeIDTemp) {
                if (!list.contains(s))
                    list.add(s);
            }
            knowledgeID = new String[list.size()];
            for(int i=0;i<list.size();i++)
                knowledgeID[i] = list.get(i).toString();
        }
        return knowledgeID;
    }

    private List<QuestionBank> getQBanks(List<PaperContent> paperLis,String positions) throws Exception {
        String[] types = new String[paperLis.size()];
        Integer[] nums = new Integer[paperLis.size()];
        String[] kids = new String[paperLis.size()];
        int cnt=0;
        for (PaperContent pcontent:paperLis){
            types[cnt] = pcontent.getTopicType();
            nums[cnt] = pcontent.getTotalTopics();
            kids[cnt] = pcontent.getKid();
            cnt++;
        }

        return (List<QuestionBank>) paperManageService.getQuestionListRandom(kids,types,nums,positions);
    }

    private List<PaperContent> getPaperContentsListJson(JSONArray jsonArray) {
        List<PaperContent> paperListTemp = new ArrayList<>();
        int num = 0;
        if (jsonArray.size() > 0) {
            for (int i=0;i< jsonArray.size();i++) {
                PaperContent paperContentTemp = new PaperContent();
                paperContentTemp.setId(String.valueOf (((JSONObject) jsonArray.get(i)).get("id")));
                paperContentTemp.setPid(String.valueOf (((JSONObject) jsonArray.get(i)).get("pid")));
                paperContentTemp.setChapter(String.valueOf (((JSONObject) jsonArray.get(i)).get("paperChapter")));
                paperContentTemp.setTopicType(String.valueOf (((JSONObject) jsonArray.get(i)).get("topicType")));
                paperContentTemp.setKid(String.valueOf (((JSONObject) jsonArray.get(i)).get("kid")));
                paperContentTemp.setTotalTopics(Integer.valueOf(String.valueOf (((JSONObject) jsonArray.get(i)).get("totalTopics"))));
                paperContentTemp.setScoreQuestion(Integer.valueOf(String.valueOf (((JSONObject) jsonArray.get(i)).get("scoreQuestion"))));
              //  paperContentTemp.setSort(Integer.valueOf(String.valueOf (((JSONObject) jsonArray.get(i)).get("sort"))));
                paperContentTemp.setSort(1);
                num++;
                paperListTemp.add(paperContentTemp);
            }
        }
        return paperListTemp;
    }

    /**
     * 修改编辑试卷
     * @param response
     * @param request
     */
    @RequestMapping(value = "/editPaper", method = RequestMethod.POST)
    @ResponseBody
    public void editPaper(HttpServletResponse response,HttpServletRequest request) {
        try {
            //获取前端数据
            PaperManage paperManageTemp = getPaperDataManage(request);

            JSONArray jsonArray = JSONArray.fromObject(request.getParameter("listJson"));
            List<PaperContent> paperListTemp = getPaperContentsListJson(jsonArray);

            List<QuestionBank> questionBankList = getQBanks(paperListTemp,paperManageTemp.getPosition());

            String paperID = request.getParameter("id");

            paperManageTemp.setId(paperID);
            paperManageTemp.setAddName(request.getParameter("addName"));
            paperManageTemp.setAddTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(request.getParameter("addTime")));
            paperManageTemp.setState(request.getParameter("paperState"));

            for(int i=0;i<paperListTemp.size();i++){
                if((paperListTemp.get(i).getId().equals("")) || (paperListTemp.get(i).getId()==null)){
                    paperListTemp.get(i).setId(UUID.randomUUID().toString());
                    paperListTemp.get(i).setPid(paperID);
                }
            }

            List<PaperContent> paperListDel = paperManageService.getPapers(paperID);
            List<PaperTopic> paperTopicListTemp = paperManageService.getPaperTopicList(paperID,"num");

            boolean flag = paperManageService.editPaper(paperManageTemp,paperListDel,paperListTemp,questionBankList,paperTopicListTemp);

            if(flag)
                utilService.printJsonResult(true, "操作成功！", "no", response);
            else
                utilService.printJsonResult(false, "操作失败！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    /**
     * 删除试卷
     * @param response
     * @param request
     */
    @RequestMapping(value = "/delPaper")
    @ResponseBody
    public void delPaper(HttpServletResponse response,HttpServletRequest request) {
        try {
            String[] paperIDs = request.getParameterValues("id");//试卷信息ID
            String delFlag = request.getParameter("delFlag");//是否包含非停用试卷

            boolean flag = paperManageService.delPaper(paperIDs);
            if(flag)
                if(delFlag.equals("true"))
                    utilService.printJsonResult(true, "已删除停用的试卷，其他无变化！", "no", response);
                else
                    utilService.printJsonResult(true, "操作成功！", "no", response);
            else
                utilService.printJsonResult(false, "操作失败！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    /**
     * 停用试卷
     * @param response
     * @param request
     */
    @RequestMapping(value = "/enablePaper")
    @ResponseBody
    public void enablePaper(HttpServletResponse response,HttpServletRequest request) {
        try {
            String[] paperIDs = request.getParameterValues("id");//试卷信息ID
            boolean flag = paperManageService.editClosePaper(paperIDs);
            if(flag)
                utilService.printJsonResult(true, "操作成功！", "no", response);
            else
                utilService.printJsonResult(false, "操作失败！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    /**
     * 试卷管理页面加载
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/topic")
    public String topic(Model model,HttpServletRequest request, HttpServletResponse response) {
        try {
            String paperID = request.getParameter("id");
            PaperManage paperManage = paperManageService.getPaperManage(paperID);
            model.addAttribute("major", paperManage.getPosition());

            model.addAttribute("pname",paperManage.getName());
            model.addAttribute("pid",paperID);

            //获取该试卷的题型情况
            List<PaperContent> paperCTypes = paperManageService.getPaperCTByChapter(paperManage.getId());

            //获取改试卷的题型列表
            List<PaperContent> paperContentListALL =  paperManageService.getPapers(paperID);
            //获取试卷内容列表
            List<PaperTopic> paperTopicListAll = paperManageService.getPaperTopicList(paperID,"num");
            //获取该试卷包含的知识点ID情况
            List<PaperContent> PaperContentKids = paperManageService.getPaperCTByKnow(paperID);
            String kids[] = new String[PaperContentKids.size()];
            int num = 0;
            for(PaperContent paperContents : PaperContentKids){
                kids[num] = paperContents.getKid();
                num++;
            }

            Integer[] flag = getFlag(paperCTypes);

            String[] typeString = {"单项选择题","不定项选择题","填空题","判断正误题","简答题","综合题"};
            String[] itemString = {"sChoose","mChoose","completion","trues","simples","summary"};
            for(int m=0;m<6;m++){
                if(flag[m] == 1){
                    JSONArray jsonArrays =  getContentOut(paperContentListALL, paperTopicListAll,typeString[m],kids);
                    model.addAttribute("titleType"+m, jsonArrays.get(0));
                    model.addAttribute("count"+m, jsonArrays.get(1));
                    model.addAttribute("tnum"+m, jsonArrays.get(2));
                    model.addAttribute("tContent"+m, jsonArrays.get(3));
                    model.addAttribute(itemString[m],jsonArrays.get(4));
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/topicPaper";
    }

    public static Integer[] getFlag(List<PaperContent> paperCTypes) {
        Integer[] flagTemp = {0, 0, 0, 0, 0, 0};
        for (PaperContent paperCType : paperCTypes) {
            if (paperCType.getTopicType().equals("单项选择题")) {
                flagTemp[0] = 1;
            } else if (paperCType.getTopicType().equals("不定项选择题")) {
                flagTemp[1] = 1;
            } else if (paperCType.getTopicType().equals("填空题")) {
                flagTemp[2] = 1;
            } else if (paperCType.getTopicType().equals("判断正误题")) {
                flagTemp[3] = 1;
            } else if (paperCType.getTopicType().equals("简答题")) {
                flagTemp[4] = 1;
            } else if (paperCType.getTopicType().equals("综合题")) {
                flagTemp[5] = 1;
            }
        }
        return flagTemp;
    }

    @ResponseBody
    @RequestMapping(value = "/getSelectQuesLayui", method = RequestMethod.GET)
    public LayuiDataTableResultBean getSelectQuesLayui(Model model,HttpServletRequest request, HttpServletResponse response){
        try {
            String tid = request.getParameter("tid");
            String pid = request.getParameter("pid");
            String major = request.getParameter("major");

            List<PaperTopic> paperTopicList = paperManageService.getPaperTopicList(pid,"type");
            String[] tids = new  String[paperTopicList.size()];
            int n = 0;
            for(PaperTopic paperTopicTemp : paperTopicList){
                tids[n] = paperTopicTemp.getTid();
                n++;
            }
            List<QuestionBank> questionBankList = paperManageService.getTopicList(tids);
            List<KnowManage> knowManageList = getKnowManaList(major);

            JSONArray jsonArray = new JSONArray();
            int num = 0;
            String strTemp = "";
            for (QuestionBank questionBank :questionBankList ){
                JSONObject jsonObject = new  JSONObject();
                jsonObject.put("idnum",num);
                int number =  getTopicNum(paperTopicList, questionBank.getId());
                jsonObject.put("number",number);
                jsonObject.put("rel","tid="+questionBank.getId()+"&pid="+pid);
                jsonObject.put("name",questionBank.getData());
                jsonObject.put("type",questionBank.getType());
                jsonObject.put("knowID",questionBank.getKid());
                String kname =  getKnowName(knowManageList, questionBank.getKid());
                jsonObject.put("knowledge",kname);
                jsonObject.put("changed",false);
                jsonArray.add(jsonObject);
                num++;
            }

            if(paperTopicList.size() > questionBankList.size()){
                for(int i =0;i<paperTopicList.size();i++){
                    boolean findCnt = false;
                    for(int j =0;j<questionBankList.size();j++){
                        if(paperTopicList.get(i).getTid().equals(questionBankList.get(j).getId())){
                            findCnt = true;
                            break;
                        }
                    }
                    if(!findCnt){
                        JSONObject jsonObject = new  JSONObject();
                        jsonObject.put("idnum",num);
                        jsonObject.put("number",paperTopicList.get(i).getNum());
                        jsonObject.put("rel","tid="+paperTopicList.get(i).getTid()+"&pid="+pid);
                        jsonObject.put("name",noFindResult);
                        jsonObject.put("type",paperTopicList.get(i).getType());
                        jsonObject.put("knowID",paperTopicList.get(i).getKid());
                        String kname =  getKnowName(knowManageList, paperTopicList.get(i).getKid());
                        jsonObject.put("knowledge",kname);
                        jsonObject.put("changed",false);
                        jsonArray.add(jsonObject);
                        num++;
                    }
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount(num);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    private int getTopicNum(List<PaperTopic> paperTopicList, String str) {
        int idNumTemp = 0;
        for(PaperTopic paperTopicTemp : paperTopicList){
            if(paperTopicTemp.getTid().equals(str)){
                idNumTemp = paperTopicTemp.getNum();
                break;
            }
        }
        return idNumTemp;
    }

    private JSONArray getContentOut(List<PaperContent> paperContentListALL,List<PaperTopic> paperTopicListAll, String  strType,String[] kids) throws Exception {
        //获取相应题型的列表
        List<PaperContent>  paperContentList = getCListByType(paperContentListALL,strType);
        //获取相应题型的试题列表
        List<PaperTopic> pTListTemp = getTopicByType(paperTopicListAll,strType);

        String[] tids = new  String[pTListTemp.size()];
        int t =0;
        for(PaperTopic paperTopic : pTListTemp){
            tids[t] = paperTopic.getTid();
            t++;
        }

        //获取相应题型的试题列表的题目情况
      //  List<QuestionBank> qBankListTemp = paperManageService.getTopicListByKidType(kids,strType);
        List<QuestionBank> qBankListTemp = paperManageService.getTopicList(tids);

        JSONArray jsonArrayTemp = new JSONArray();
        jsonArrayTemp.add(strType);
        jsonArrayTemp.add(pTListTemp.size());

        int num;
        String tContent0 = "";
        String tname = "";
        List<Map<String, Object>> listTemp = new ArrayList<Map<String, Object>>();
        num = 0;
        for(PaperTopic paperTopicTemp : pTListTemp){
            //获取题干
            tname = getQName(paperTopicTemp.getTid(), qBankListTemp);
            if(num == 0){
                tContent0 = tname;
                jsonArrayTemp.add("tid="+paperTopicTemp.getTid()+"&pid="+paperTopicTemp.getPid());
                jsonArrayTemp.add(tContent0);//题干
            }else {
                Map mapTemp = new HashMap<>();
                mapTemp.put("tN","tid="+paperTopicTemp.getTid()+"&pid="+paperTopicTemp.getPid());
                mapTemp.put("tContent", tname);
                listTemp.add(mapTemp);
            }
            num++;
        }

        if(num > 1)
            jsonArrayTemp.add(listTemp);

        return jsonArrayTemp;
    }

    private  List<PaperTopic>  getTopicByType(List<PaperTopic> paperTList,String str) {
        List<PaperTopic> pTopList = new ArrayList();
        for(PaperTopic pTopic : paperTList){
            if(pTopic.getType().equals(str)){
                pTopList.add(pTopic);
            }
        }
        return pTopList;
    }

    private  List<PaperContent> getCListByType(List<PaperContent> paperContent,String str) {
        List<PaperContent> pConList = new ArrayList();
        for(PaperContent paperCon : paperContent){
            if(paperCon.getTopicType().equals(str)){
                pConList.add(paperCon);
            }
        }
        return pConList;
    }

    private String getQName(String str, List<QuestionBank> qbTemp) {
        String tnameTemp = "";
        for(QuestionBank questionBankTemp : qbTemp){
            if(questionBankTemp.getId().equals(str)){
                tnameTemp = questionBankTemp.getData();
                break;
            }
        }
        if(tnameTemp.equals(""))
            tnameTemp = noFindResult;
        return tnameTemp;
    }
    @RequestMapping("/choose")
    public String choose(Model model,HttpServletRequest request, HttpServletResponse response) {
        try {
            String tid = request.getParameter("tid");
            String pid = request.getParameter("pid");
            String major = request.getParameter("major");

            PaperTopic paperTopic = paperManageService.getTopicByTPid(tid,pid);
            KnowManage knowManage = paperManageService.getKnowManageByID(paperTopic.getKid());
/*
            List<Knowledge> knowledgeList = paperManageService.getKnowledgeListGroup(major);

            String[] kids = new String[knowledgeList.size()];
            int n = 0;
            for(Knowledge knowledge : knowledgeList){
                kids[n] = knowledge.getKid();
                n++;
            }
            List<KnowManage> knowManageList = paperManageService.getKnowManageList(kids);
            model.addAttribute("kidnames",knowManageList);
            */

            model.addAttribute("kidnames",knowManage.getName());
            model.addAttribute("tid",tid);
            model.addAttribute("pid",pid);
            model.addAttribute("kid",knowManage.getId());
            model.addAttribute("major",major);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/topicChoose";
    }

    /**
     * 获取问题列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/SelectQuestion", method = RequestMethod.GET)
    public LayuiDataTableResultBean SelectQuestion(Model model,HttpServletRequest request, HttpServletResponse response) {
        try {
            int curPage = Integer.parseInt(request.getParameter("page"));
            int pageSize = Integer.parseInt(request.getParameter("limit"));

            String tid = request.getParameter("tid");
            String pid = request.getParameter("pid");
            String kid = request.getParameter("kid");
            String major = request.getParameter("major");

            String keyWord = (request.getParameter("key[tkey]")==null)?"":request.getParameter("key[tkey]");

            int keyLevel = -1;
            try {
                keyLevel = Integer.parseInt(request.getParameter("key[tLevel]"));
            } catch (NumberFormatException ignored) {
            }

           /* String keyKonwledge  = request.getParameter("key[tKonwledge]");
            String keyKonwledgeID ="";
            if(keyKonwledge != null){
                KnowManage keyKonwManage = paperManageService.getKnowManageByName(keyKonwledge);
                keyKonwledgeID = keyKonwManage.getId();
            }*/
            PaperTopic paperTopicTemp = paperManageService.getTopicByTPid(tid,pid);
            String typeStr = paperTopicTemp.getType();

            List<KnowManage> knowManageList = getKnowManaList(major);

            //Map<String, Object> map = paperManageService.getQuestionList(curPage, pageSize, keyKonwledgeID,keyLevel, typeStr,keyWord);
            Map<String, Object> map = paperManageService.getQuestionList(curPage, pageSize, kid, keyLevel, typeStr,keyWord,major);
            double count = (double) map.get("count");
            double pageCount = (Double) map.get("pageCount");
            JSONArray jsonArray = new JSONArray();

            int num = 0;
            if (pageCount != 0) {
                Object object = map.get("list");
                for (QuestionBank questionBank :(List<QuestionBank>) object){
                    JSONObject jsonObject = new  JSONObject();
                    jsonObject.put("idnum",num);
                    jsonObject.put("number",0);
                    jsonObject.put("rel","tid="+questionBank.getId()+"&pid="+pid);
                    jsonObject.put("name",questionBank.getData());
                    jsonObject.put("type",questionBank.getType());
                    String kname =  getKnowName(knowManageList, questionBank.getKid());
                    jsonObject.put("knowID",questionBank.getKid());
                    jsonObject.put("knowledge",kname);
                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) count);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    private List<KnowManage> getKnowManaList(String major) throws Exception {
        List<Knowledge> knowledgeList = paperManageService.getKnowledgeListGroup(major);

        String[] kids = new String[knowledgeList.size()];
        int n = 0;
        for(Knowledge knowledge : knowledgeList){
            kids[n] = knowledge.getKid();
            n++;
        }
        return paperManageService.getKnowManageList(kids);
    }

    private String getKnowName(List<KnowManage> knowManageList, String str) {
        String knameTemp = "";
        for(KnowManage knowManage : knowManageList){
            if(knowManage.getId().equals(str)){
                knameTemp = knowManage.getName();
            }
        }
        return  knameTemp;
    }

    /**
     * 查看试卷
     * @param
     * @param response
     * @return
     */
    @RequestMapping("/seePaper")
    public String seePaper(Model model,HttpServletRequest request, HttpServletResponse response) {
        try {
            String paperID = request.getParameter("id");
            PaperManage paperManage = paperManageService.getPaperManage(paperID);
            List<PaperContent> paperContentListTemp = paperManageService.getPapers(paperID);

            model.addAttribute("paperName",paperManage.getName());
            String paperType = paperManage.getType().equals("0")?"固定试卷":"随机试卷";
            model.addAttribute("paperType",paperType);
            model.addAttribute("paperPurpose",paperManage.getPurpose().equals("0")?"练习用卷":"考试用卷");
            model.addAttribute("paperNameTitle",paperType);
         //   model.addAttribute("position",paperManage.getPosition());
            model.addAttribute("totalScore",paperManage.getTotalScore());
            model.addAttribute("paperState",paperManage.getState());
            model.addAttribute("addName",paperManage.getAddName());
            model.addAttribute("addTime",DateTools.toLenStr(paperManage.getAddTime()));
            model.addAttribute("paperExplain",paperManage.getExplain());

            //获取该试卷的所有题型
            List<PaperContent> paperCTypes = paperManageService.getPaperCTByChapter(paperManage.getId());

            Integer[] flag = getFlag(paperCTypes);

            //获取改试卷的题型列表
            List<PaperContent> paperContentListALL =  paperManageService.getPapers(paperID);

            //获取该试卷包含的知识点ID情况
            List<PaperContent> PaperContentKids = paperManageService.getPaperCTByKnow(paperID);
            String kids[] = new String[PaperContentKids.size()];
            int num = 0;
            for(PaperContent paperContents : PaperContentKids){
                kids[num] = paperContents.getKid();
                num++;
            }
            //获取试卷内容列表
            List<PaperTopic> paperTopicListAll = paperManageService.getPaperTopicList(paperID,"num");

            if(paperType.equals("随机试卷")){
                List<QuestionBank> questionBankList = getQBanks(paperContentListTemp,paperManage.getPosition());
                paperTopicListAll = paperManageService.editTopicRandom(paperManage,paperContentListTemp,paperTopicListAll,questionBankList);
            }

            String[] typeString = {"单项选择题","不定项选择题","填空题","判断正误题","简答题","综合题"};
            String[] itemString = {"sChoose","mChoose","completion","trues","simples","summary"};
            String[] tNum = {"一","二","三","四","五","六"};
            String[] tChoo = {"A、 ","B、 ","C、 ","D、 ","E、 ","F、 ","G、 ","H、 ","I、 ","J、 ","K、 ","I、 ",
                            "L、 ","M、 ","N、 "};

            boolean findFlag = true;

            for(int n = 0;n<2;n++){
                if ((flag[n] == 1)&&(findFlag)) {
                    String strType = typeString[n];
                    //获取相应题型的列表
                    List<PaperContent>  paperContentList = getCListByType(paperContentListALL, strType);
                    //获取相应题型的试题列表
                    List<PaperTopic> pTListTemp = getTopicByType(paperTopicListAll,strType);
                    //获取相应题型的试题列表的题目情况
                    List<QuestionBank> qBankListTemp = paperManageService.getTopicListByKidType(kids,strType);

                    List<Map<String, Object>> listTemp = new ArrayList<Map<String, Object>>();

                    for(PaperTopic paperTopicT : pTListTemp){
                        QuestionBank questBankTemp =  getQuestion(qBankListTemp,paperTopicT.getTid());

                        if(questBankTemp.getId() == null){
                            findFlag = false;
                            break;
                        }else{
                            Map mapTemp = new HashMap<>();
                            mapTemp.put("tN", paperTopicT.getNum());
                            mapTemp.put("tContent", questBankTemp.getData());

                            if(num < 2){
                                String[] getStr = questBankTemp.getOptions().substring(1,questBankTemp.getOptions().length()-1).split(",");
                                for(int m = 0; m<getStr.length;m++)
                                    mapTemp.put("tNS"+m, tChoo[m]+getStr[m].substring(1,getStr[m].length()-1));
                            }
                            listTemp.add(mapTemp);
                        }

                    }

                    int scnt = 0;int tcnt =0;

                    for(PaperContent paperContent : paperContentList){
                        scnt = scnt + paperContent.getScoreQuestion();
                        tcnt = tcnt +paperContent.getTotalTopics();
                    }
                    model.addAttribute("titleNum"+n, paperContentList.get(0).getChapter());
                    model.addAttribute("titleType"+n, strType);
                    model.addAttribute("scoreQuestion"+n, scnt);
                    model.addAttribute("totalTopics"+n,tcnt);
                    model.addAttribute("allCount"+n, scnt*tcnt);

                    model.addAttribute(itemString[n].toString(),listTemp);
                }
            }

            for(int n = 2;n<6;n++){
               if ((flag[n] == 1)&&(findFlag)) {
                   String strType = typeString[n];
                   JSONArray jsonArrayTemp =  getTopicView(paperContentListALL,paperTopicListAll, kids, typeString[n],
                           tChoo,itemString[n],n,findFlag);

                   findFlag = (boolean) jsonArrayTemp.get(7);

                   model.addAttribute("titleNum"+n, jsonArrayTemp.get(0));
                   model.addAttribute("titleType"+n, jsonArrayTemp.get(1));
                   model.addAttribute("scoreQuestion"+n, jsonArrayTemp.get(2));
                   model.addAttribute("totalTopics"+n,jsonArrayTemp.get(3));
                   model.addAttribute("allCount"+n, jsonArrayTemp.get(4));

                   model.addAttribute(jsonArrayTemp.get(5).toString(),jsonArrayTemp.get(6));
               }
           }
            model.addAttribute("findFlag", findFlag ?1:0);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/viewPaper";
    }

    private JSONArray getTopicView(List<PaperContent> pCListALL,List<PaperTopic> pTListAll, String[] kidsTemp,String strType,
                                   String[] tChoos, String tType,Integer num,boolean findFlag) throws Exception {

        JSONArray jsonArrayT = new JSONArray();
        //获取相应题型的列表
        List<PaperContent>  paperContentList = getCListByType(pCListALL, strType);
        //获取相应题型的试题列表
        List<PaperTopic> pTListTemp = getTopicByType(pTListAll,strType);
        //获取相应题型的试题列表的题目情况
        List<QuestionBank> qBankListTemp = paperManageService.getTopicListByKidType(kidsTemp,strType);
        int scnt = 0;
        int tcnt = 0;
        for(PaperContent paperContent : paperContentList){
            scnt = scnt + paperContent.getScoreQuestion();
            tcnt = tcnt +paperContent.getTotalTopics();
        }

        jsonArrayT.add(paperContentList.get(0).getChapter());
        jsonArrayT.add(strType);
        jsonArrayT.add(scnt);
        jsonArrayT.add(tcnt);
        jsonArrayT.add(scnt*tcnt);
        jsonArrayT.add(tType);

        List<Map<String, Object>> listTemp = new ArrayList<Map<String, Object>>();

        for(PaperTopic paperTopicT : pTListTemp){
            QuestionBank questBankTemp =  getQuestion(qBankListTemp,paperTopicT.getTid());

            if(questBankTemp.getId() == null){
                findFlag = false;
                break;
            }else {
                Map mapTemp = new HashMap<>();
                mapTemp.put("tN", paperTopicT.getNum());
                String tname = "";
                if (strType.equals("填空题")) {
                    String ts = questBankTemp.getData();
                    int len1 = getWordCount(ts, "[");
                    int len2 = getWordCount(ts, "]");
                    int len = Math.min(len1, len2);
                    for (int k = 1; k < (len + 1); k++) {
                        ts = ts.replace("[" + k + "]", "（                ）");
                    }
                    tname = ts;
                } else
                    tname = questBankTemp.getData();
                mapTemp.put("tContent", tname);
                listTemp.add(mapTemp);
            }
        }

        jsonArrayT.add(listTemp);
        jsonArrayT.add(findFlag);

        return jsonArrayT;
    }

    private Integer getWordCount(String str,String s) {
        Integer count = 0;
        while(str.indexOf(s) != -1) {
            str = str.substring(str.indexOf(s) + 1,str.length());
            count++;
        }
        return  count;
    }

    private QuestionBank getQuestion(List<QuestionBank> qBankLTemp,String str) {
        QuestionBank questBank = new QuestionBank();
        for(QuestionBank questionBankT : qBankLTemp){
            if(questionBankT.getId().equals(str))
                questBank = questionBankT;
        }
        return questBank;
    }

    @RequestMapping(value = "/seePaperList")
    @ResponseBody
    public void seePaperList(HttpServletResponse response,HttpServletRequest request) {
        try {
            String[] paperIDs = request.getParameterValues("id");//试卷信息ID
            boolean flag = paperManageService.editClosePaper(paperIDs);
            if(flag)
                utilService.printJsonResult(true, "操作成功！", "no", response);
            else
                utilService.printJsonResult(false, "操作失败！", "no", response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }


    /**
     * 获取前端发来的数据1
     * @param request
     * @return
     */
    private PaperManage getPaperDataManage(HttpServletRequest request) {
        String paperName = request.getParameter("paperName");
        String paperPurpose = request.getParameter("paperPurpose");
        String paperType = request.getParameter("paperType");
        String position = request.getParameter("position");
        Integer totalScore = Integer.valueOf(request.getParameter("totalScore"));
      //  String paperState = request.getParameter("paperState");
        String paperExplain = request.getParameter("paperExplain");

        PaperManage paperManageTemp = new PaperManage();
        paperManageTemp.setName(paperName);
        paperManageTemp.setPurpose(paperPurpose);
        paperManageTemp.setType(paperType);
        paperManageTemp.setPosition(position);
        paperManageTemp.setTotalScore(totalScore);
      //  paperManageTemp.setState(paperState);
        paperManageTemp.setExplain((paperExplain.equals(""))?"无":paperExplain);

        return paperManageTemp;
    }

    /**
     * 保存更改题目
     * @param request
     * @param response
     */
    @RequestMapping(value = "/saveQuestion")
    public void saveQuestion(HttpServletRequest request, HttpServletResponse response){
        try {
            String paperID = request.getParameter("id");//试卷信息ID
            String paperName = request.getParameter("pname");//试卷名称

            JSONArray jsonArray = JSONArray.fromObject(request.getParameter("chdata"));
            List<PaperTopic> paperTopicList = paperManageService.getPaperTopicList(paperID,"type");

            boolean flag = paperManageService.editTopic(paperTopicList,jsonArray);

            if(flag){
                utilService.printJsonResult(true,"操作成功！","",response);
            }else
                utilService.printJsonResult(false,"操作失败！","",response);
        }catch (Exception e){
            e.printStackTrace();
            utilService.printJsonResult(false,"操作失败！","",response);
        }
    }
    /**
     * 导出试卷
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportPaper")
    public void exportPaper(HttpServletRequest request, HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin","*");
        try {
            String[] paperIDs = request.getParameterValues("id");//试卷信息ID
            String strs = "";
            boolean resultFlag = false;
            int num = 0;
            if (paperIDs != null) {
                for (String paperID : paperIDs) {
                    PaperManage paperManage = paperManageService.getPaperManage(paperID);
                    String headPath="F:/tomcat_ZPQT/webapps/myHrWeb/";
                    String savePath=request.getSession().getServletContext().getRealPath("/resources/ResumeAppends/"+paperManage.getName()+"/");

                    resultFlag = createWordPaper(paperManage,savePath,headPath);
                    if(resultFlag){
                        strs +=  "/resources/ResumeAppends/"+paperManage.getName()+"/"+paperManage.getName()+"_试卷.doc,";
                        num++;
                    }
                }
            }
            if(num >= paperIDs.length){
                utilService.printJsonResult(true,"操作成功！",strs,response);
            }if(num > 0){
                utilService.printJsonResult(false,"部分试卷操作成功，导出失败的试卷" +noFindResult,"",response);
            } else
                utilService.printJsonResult(false,"操作失败！","",response);
        }catch (Exception e){
            e.printStackTrace();
            utilService.printJsonResult(false,"操作失败！","",response);
        }
    }

    /**
     * 生成考试试卷
     * @param paperManage
     * @param savePath
     * @param headPath
     */
    private boolean createWordPaper(PaperManage paperManage, String savePath, String headPath) throws Exception {
        try {

            Map resumeMap = new HashMap<>();

            String paperID = paperManage.getId();
            resumeMap.put("paperName",paperManage.getName());
            String paperType = paperManage.getType().equals("0")?"固定试卷":"随机试卷";
            resumeMap.put("paperType",paperType);
            resumeMap.put("paperPurpose",(paperManage.getPurpose().equals("0")?"练习用卷":"考试用卷"));
            resumeMap.put("paperNameTitle",paperType);
            //   resumeMap.put("position",paperManage.getPosition());
            resumeMap.put("totalScore",paperManage.getTotalScore());
            resumeMap.put("paperState",paperManage.getState());
            resumeMap.put("addName",paperManage.getAddName());
            resumeMap.put("addTime",DateTools.toLenStr(paperManage.getAddTime()));
            resumeMap.put("paperExplain",paperManage.getExplain());

            List<PaperContent> paperCTypes = paperManageService.getPaperCTByChapter(paperManage.getId());
            Integer[] flag = getFlag(paperCTypes);

            //获取改试卷的题型列表
            List<PaperContent> paperContentListALL =  paperManageService.getPapers(paperID);

            //获取该试卷包含的知识点ID情况
            List<PaperContent> PaperContentKids = paperManageService.getPaperCTByKnow(paperID);
            String kids[] = new String[PaperContentKids.size()];
            int num = 0;
            for(PaperContent paperContents : PaperContentKids){
                kids[num] = paperContents.getKid();
                num++;
            }

            //获取试卷内容列表
            List<PaperTopic> paperTopicListAll = paperManageService.getPaperTopicList(paperID,"num");
            List<PaperContent> paperContentListTemp = paperManageService.getPapers(paperID);

            if(paperType.equals("随机试卷")){
                List<QuestionBank> questionBankList = getQBanks(paperContentListTemp,paperManage.getPosition());
                paperTopicListAll = paperManageService.editTopicRandom(paperManage,paperContentListTemp,paperTopicListAll,questionBankList);
            }

            String[] typeString = {"单项选择题","不定项选择题","填空题","判断正误题","简答题","综合题"};
            String[] itemString = {"sChoose","mChoose","completion","trues","simples","summary"};
            String[] tNum = {"一","二","三","四","五","六"};
            String[] tChoo = {"A、 ","B、 ","C、 ","D、 ","E、 ","F、 ","G、 ","H、 ","I、 ","J、 ","K、 ","I、 ",
                    "L、 ","M、 ","N、 "};

            boolean findFlag = true;

            for(int n = 0;n<2;n++){
                if ((flag[n] == 1)&&(findFlag)) {
                    String strType = typeString[n];
                    //获取相应题型的列表
                    List<PaperContent> paperContentList = getCListByType(paperContentListALL, strType);
                    //获取相应题型的试题列表
                    List<PaperTopic> pTListTemp = getTopicByType(paperTopicListAll, strType);
                    //获取相应题型的试题列表的题目情况
                    List<QuestionBank> qBankListTemp = paperManageService.getTopicListByKidType(kids, strType);


                    List<Map<String, Object>> listTemp = new ArrayList<Map<String, Object>>();

                    for (PaperTopic paperTopicT : pTListTemp) {
                        QuestionBank questBankTemp = getQuestion(qBankListTemp, paperTopicT.getTid());

                        if(questBankTemp.getId() == null){
                            findFlag = false;
                            break;
                        }else {
                            Map mapTemp = new HashMap<>();
                            mapTemp.put("tN", paperTopicT.getNum());
                            mapTemp.put("tContent", questBankTemp.getData());

                            if (n < 2) {
                                String[] getStr = questBankTemp.getOptions().substring(1, questBankTemp.getOptions().length() - 1).split(",");
                                for (int m = 0; m < getStr.length; m++)
                                    mapTemp.put("tNS" + m, tChoo[m] + getStr[m].substring(1, getStr[m].length() - 1));
                            }
                            listTemp.add(mapTemp);
                        }
                    }

                    int scnt = 0;
                    int tcnt = 0;
                    for (PaperContent paperContent : paperContentList) {
                        scnt = paperContent.getScoreQuestion();
                        tcnt = paperContent.getTotalTopics();
                    }
                    resumeMap.put("titleNum" + n, paperContentList.get(0).getChapter());
                    resumeMap.put("titleType" + n, strType);
                    resumeMap.put("scoreQuestion" + n, scnt);
                    resumeMap.put("totalTopics" + n, tcnt);
                    resumeMap.put("allCount" + n, scnt * tcnt);

                    resumeMap.put(itemString[n].toString(), listTemp);
                }
            }

            for(int n = 2;n<6;n++){
                if ((flag[n] == 1)&&(findFlag)) {
                    String strType = typeString[n];
                    JSONArray jsonArrayTemp =  getTopicView(paperContentListALL,paperTopicListAll, kids, typeString[n],
                            tChoo,itemString[n],n,findFlag);

                    findFlag = (boolean) jsonArrayTemp.get(7);

                     resumeMap.put("titleNum"+n, jsonArrayTemp.get(0));
                     resumeMap.put("titleType"+n, jsonArrayTemp.get(1));
                     resumeMap.put("scoreQuestion"+n, jsonArrayTemp.get(2));
                     resumeMap.put("totalTopics"+n,jsonArrayTemp.get(3));
                     resumeMap.put("allCount"+n, jsonArrayTemp.get(4));

                     resumeMap.put(jsonArrayTemp.get(5).toString(),jsonArrayTemp.get(6));
                }
            }

            if(findFlag){
                WordByFreeMarker word = new WordByFreeMarker();
                String tempName = "试卷.ftl";

                word.createWord(resumeMap, tempName, savePath + "/" + paperManage.getName() + "_试卷.doc");
            }
            return findFlag;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 试卷答案页面加载
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/answer")
    public String answer(Model model,HttpServletRequest request) {
        try {
            String pid = request.getParameter("id");

            PaperManage paperManage = null;

            if (StringTools.trimNotEmpty(pid))
                paperManage=  paperManageService.getPaperManage(pid);

            model.addAttribute("pid",pid);
            model.addAttribute("paperName",paperManage.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "exam/PaperManager/topicAnswer";
    }

    /**
     * 获取试卷答案列表
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getAnswer", method = RequestMethod.GET)
    public LayuiDataTableResultBean getAnswer(HttpServletRequest request, HttpServletResponse response){
        try {
            String pid = request.getParameter("pid");

            List<PaperTopic> paperTopics = paperManageService.getPaperTopicList(pid,"num");

            String[] tids = new  String[paperTopics.size()];
            int num = 0;
            for(PaperTopic paperTopic :paperTopics){
                tids[num] = paperTopic.getTid();
                num++;
            }
            List<QuestionBank> questionBankList = paperManageService.getTopicList(tids);

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            if(paperTopics.size() > questionBankList.size()){
                result.setCount(-1);
                result.setMsg("dataError");
            }else {
                String[] typeString = {"单项选择题","不定项选择题","填空题","判断正误题","简答题","综合题"};

                num = 0;
                JSONArray jsonArray = new JSONArray();
                for(int i =0;i<questionBankList.size();i=i+2){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("num1",i+1);
                    if(questionBankList.get(i).getType().equals(typeString[0])||questionBankList.get(i).getType().equals(typeString[1])||
                            questionBankList.get(i).getType().equals(typeString[3]))
                        jsonObject.put("answer1",questionBankList.get(i).getChoose()==null?"":questionBankList.get(i).getChoose());
                    else
                        jsonObject.put("answer1",questionBankList.get(i).getAnswer()==null?"":questionBankList.get(i).getAnswer());

                    if(i<(questionBankList.size()-1)){
                        jsonObject.put("num2",i+2);
                        if(questionBankList.get(i).getType().equals(typeString[0])||questionBankList.get(i).getType().equals(typeString[1])||
                                questionBankList.get(i).getType().equals(typeString[3]))
                            jsonObject.put("answer2",questionBankList.get(i+1).getChoose()==null?"":questionBankList.get(i+1).getChoose());
                        else
                            jsonObject.put("answer2",questionBankList.get(i+1).getAnswer()==null?"":questionBankList.get(i+1).getAnswer());
                    }
                    num++;
                    jsonArray.add(jsonObject);
                }

                result.setCode(0);
                result.setMsg("success");
                result.setCount(num);
                result.setData(jsonArray);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
    /**
     * 下载试卷答案
     * @param response
     * @param request
     */
    @RequestMapping(value = "/exportAnswer")
    @ResponseBody
    public void exportAnswer(HttpServletResponse response,HttpServletRequest request) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            String pid = request.getParameter("pid");
            String pname = request.getParameter("pname");

            List<PaperTopic> paperTopics = paperManageService.getPaperTopicList(pid, "num");

            String[] tids = new String[paperTopics.size()];
            int num = 0;
            for (PaperTopic paperTopic : paperTopics) {
                tids[num] = paperTopic.getTid();
                num++;
            }
            List<QuestionBank> questionBankList = paperManageService.getTopicList(tids);


            codedFileName = java.net.URLEncoder.encode(pname + "_试卷答案", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();


            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel0 = headrow.createCell(0);
            headcel0.setCellValue(new HSSFRichTextString("题目序号"));
            HSSFCell headcel1 = headrow.createCell(1);
            headcel1.setCellValue(new HSSFRichTextString("题目答案"));
            HSSFCell headcel2 = headrow.createCell(2);

            String[] typeString = {"单项选择题", "不定项选择题", "填空题", "判断正误题", "简答题", "综合题"};
            if (questionBankList.size() > 0) {
                num = 1;
                for (QuestionBank questionBank : questionBankList) {
                    HSSFCell cell;
                    HSSFRow row = sheet.createRow(num);//创建一行

                    cell = row.createCell(0);//创建一列
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(new HSSFRichTextString(String.valueOf(num)));

                    cell = row.createCell(1);//创建一列
                    cell.setCellType(CellType.STRING);
                    if (questionBank.getType().equals(typeString[0]) || questionBank.getType().equals(typeString[1]) ||
                            questionBank.getType().equals(typeString[3]))
                        cell.setCellValue(new HSSFRichTextString(questionBank.getChoose() == null ? "" : questionBank.getChoose()));
                    else
                        cell.setCellValue(new HSSFRichTextString(questionBank.getAnswer() == null ? "" : questionBank.getAnswer()));

                    num++;
                }
            }

            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {

            }
        }
    }
}
